package com.weixin.webCoding;

import org.junit.Test;

import java.io.*;
import java.net.*;

/**
 * @ClassName TcpTest02
 * @Description
 * @date 2022/2/18 10:07
 * @author: wx
 * @Version 1.0
 */
public class UdpTest {

    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String s = "我是udp发送的消息";
        byte[] bytes = s.getBytes();
        InetAddress ip = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,ip,8002);
        socket.send(packet);
        socket.close();
    }

    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(8002);

        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();
    }
}
